<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--el-card是element的卡片系统，就是view区域白色的部分-->
        <el-card>
            <!--搜索栏的栅格系统 el-row和el-col来控制-->
            <el-row :gutter="10">
                <el-col :span="10">
                        <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUsersList">
                            <!--注意 ，这个slot=append不能删除-->
                            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
                        </el-input>
                </el-col>
                <el-col :span="6">
                    <!--注意，在html的标签里面通过事件，改变data里面的值。这个不需要this调用，直接赋值就可-->
                    <el-button type='primary' :span="6" @click="addDialogVisible=true">添加用户
                    </el-button>
                </el-col>
            </el-row>
            <!--栅格系统结束-->
            <el-table border stripe
                    :data="userList"
                    style="width: 100%">
                <!--在el-table中，添加序号列，加一个el-table-column的标签，然后后面的type=index-->
                <el-table-column type="index" label="序号" width="80"></el-table-column>
                <el-table-column
                        prop="role_name"
                        label="管理类别"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="姓名"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="email"
                        label="邮箱"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="mobile"
                        label="电话"
                        width="180">
                </el-table-column>
                <el-table-column
                    label="状态">
                    <template v-slot='scope'>
                    <!--v-slot是插槽，会存放本该渲染在此行的数据，然后存储在scope里面，然后scope里面的row属性会存放-->
                        <el-switch v-model="scope.row.mg_state" @change="addChangeEvent(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="180">
                    <template v-slot="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
                        <el-button class='share' type="warning" icon="el-icon-setting" size="mini" @click="setRight(scope.row)"></el-button>
                        <!--注意：如果赋值的是boolean需要v-bind绑定-->
                        <el-tooltip effect="dark" content="删除当前管理员" placement="top-start" :enterable="false">
                            <el-button class='delete' type="danger" icon="el-icon-delete" size="mini" @click="delUserByID(scope.row.id)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!--dialog对话框-->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%"
                >
            <el-form :model="addForm" :rules="addRules" ref="addRuleFormRef" label-width="70px" @close="addDialogClose">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
        </el-dialog>
        <!--dialog结束标签-->
        <!--编辑用户的dialog对话框-->
        <el-dialog
                title="编辑用户信息"
                :visible.sync="editUserVisible"
                width="30%"
                >
            <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px" @close="editClose">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
        </el-dialog>
      <el-dialog
          title="选择用户权限"
          :visible.sync="chooseRightVisiable"
          width="50%"
          @close="closeClearInfo"
          >
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前用户角色：{{userInfo.role_name}}</p>
        <p>给当前用户分配角色：
          <el-select v-model="selectrole" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
    <span slot="footer" class="dialog-footer">
    <el-button @click="chooseRightVisiable = false">取 消</el-button>
    <el-button type="primary" @click="getSelectedID">确 定</el-button>
  </span>
      </el-dialog>
    </div>
</template>
<script>
    export default {
        // 注意在Vue的组件里面data是函数，定义的变量需要return回来。
        // created等生命周期函数也是个函数，但是methods是一个对象写法是methods：{}
        data(){
            return{
              selectrole:'',
              rolesList:[],
              chooseRightVisiable:false,
              userInfo:'',
              editUserVisible:false,
                queryInfo:{
                    query:'',
                    pagenum:1,
                    pagesize:2
                },
                userList:[],
                total:0,
                addDialogVisible:false,
                addForm:{
                    username:'',
                    password:'',
                    email:'',
                    mobile:''
                },
                addRules:{
                    username:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur' }
                    ],
                    email:[
                      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    mobile:[
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        { min: 11, max: 11, message: '请输入正确是手机号码', trigger: 'blur' }
                    ]
                },
                editForm:{},
              editRules:{
                username:[
                  { required: true, message: '请输入用户名', trigger: 'blur' },
                  { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                email:[
                  { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                  { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                mobile:[
                  { required: true, message: '请输入手机号码', trigger: 'blur' },
                  { min: 11, max: 11, message: '请输入正确是手机号码', trigger: 'blur' }
                ]
              }
            }
        },
        created() {
            this.getUsersList()
        },
        methods:{
            async getUsersList(){
                const {data:res} =await this.$http.get('users',{params:this.queryInfo})
                console.log(res);
                if(res.meta.status!==200) return this.$message.error('获取用户列表失败')
                this.$message.success('获取用户列表成功')
                this.userList = res.data.users
                // console.log(this.userList[0].mg_state,this.userList[1].mg_state);
                this.total = res.data.total
            },
            handleSizeChange(pageSize){
                console.log(pageSize);
                this.queryInfo.pagesize=pageSize
                // 注意！！！改变了请求参数之后，需要重新请求
                this.getUsersList()
            },
            handleCurrentChange(pageNum){
                this.queryInfo.pagenum=pageNum
                this.getUsersList()
            },
            // 监听switch状态改变
            async addChangeEvent(row){
                console.log(row);
                const {data:res}=await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
                console.log(res.meta.status);
                if(res.meta.status !==200){
                    row.mg_state=!row.mg_state
                    return this.$message.error('更改状态失败')
                }
                this.$message.success('用户状态更改成功')
            },
          addDialogClose(){
              this.$refs.addRuleFormRef.resetFields()
          },
          addUser(){
            this.$refs.addRuleFormRef.validate(async validator=>{
              if (!validator) return this.$message.error('添加用户信息失败');
              // 发起网络请求
              const {data:res}=await this.$http.post('users',this.addForm)
              if(res.meta.status !== 201){
                this.$message.error('添加用户信息失败')
              }
              this.$message.success('添加用户成功')
              this.addDialogVisible =false
              // 重新获取用户列表的数据
              this.getUsersList()
            })
          },
          async editUser(id){
              this.editUserVisible=true
              const{data:res}=  await this.$http.get('users/'+id)
                if(res.meta.status !==200)
                  return this.$http.error('查询用户信息是失败')
            this.editForm=res.data
            this.editUserVisible=true
          },
          editClose(){
              this.refs.editFormRef.resetField()
          },
          editUserInfo(){
              // 注意dialog的弹框，一定要在提交之前用refs的属性找到ref，然后用validate验证
              this.$refs.editFormRef.validate(async validator=>{
                if(!validator) return
                const {data:res}= await this.$http.put('users/'+this.editForm.id,{
                  email:this.editForm.email,
                  mobile:this.editForm.mobile
                })
                if(res.meta.status!== 200){
                  return this.$message.error('更改用户信息失败')
                }
                // 关闭窗口
                this.editUserVisible=false
                // 刷新用户列表
                this.getUsersList()
                // 回馈用户信息正确
                this.$message.success('更新用户数据成功')
              })
          },
          delUserByID(id){
              this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async () => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                const {data:res}=await this.$http.delete('users/'+id)
                console.log(res);
                if(res.meta.status===200){
                  this.$message.success('删除数据成功')
                }
                this.getUsersList()
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              });
          },
          async setRight(userInfo) {
            this.userInfo = userInfo
            const{data:res}=await this.$http.get('roles')
            if(res.meta.status !==200){
              return this.$message.error('获取角色失败')
            }
            this.rolesList = res.data
            // 在展示对话框之前，获取所有角色列表
            this.chooseRightVisiable=true
          },
          // 获取用户分配菜单的下拉角色
          async getSelectedID(){
              // selectrole是通过el-select双向绑订到data里面的
            console.log(this.selectrole);
            if(!this.selectrole){
              return this.$message.error('您好，你还没选中任何权限')
            }
            console.log('得到想要改变的id',this.userInfo.id);
            console.log('得到用户选择的id',this.selectrole);
            const{data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectrole})
            if(res.meta.status !==200){
              console.log(res);
              return this.$message.error('用户修改权限失败')
            }
            this.$message.success('用户获得权限成功')
            this.getUsersList()
            this.chooseRightVisiable = false
          },
          closeClearInfo(){
              this.selectrole=''
              this.userInfo=''
          }

        }

    }

</script>
<style lang="less" scoped>


</style>